package com.kwxy.hyt.controller;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.kwxy.hyt.base.BaseController;
import com.kwxy.hyt.po.*;
import com.kwxy.hyt.utils.Pager;
import java.util.*;

import com.kwxy.hyt.po.*;
import com.kwxy.hyt.mapper.*;
import com.kwxy.hyt.service.*;

/**
 * @ClassName:  
 * @Description: 
 * @author  - - admin
 * @date - 2020年9月10日 09时48分24秒
 */


@Controller
@RequestMapping("/record")
public class RecordController extends BaseController {
	@Autowired
	private SignService signService;
	
	/**
	 * 依赖注入 start dao/service/===
	 */
	@Autowired
	private RecordService recordService;
	
	// --------------------------------------- 华丽分割线 ------------------------------
	
	/**
	 * 分页查询 返回list对象(通过对By Sql)
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/findBySql")
	public String findBySql(Record record, Model model, HttpServletRequest request, HttpServletResponse response) {
		//分页查询
		String sql = "SELECT * FROM record WHERE signId="+record.getSignId();
        if(!isEmpty(record.getSignId())){
        	sql += " and signId like '%"+record.getSignId()+"%'";
		}
        if(!isEmpty(record.getStudentId())){
        	sql += " and studentId like '%"+record.getStudentId()+"%'";
		}
        if(!isEmpty(record.getIp())){
        	sql += " and ip like '%"+record.getIp()+"%'";
		}
        if(!isEmpty(record.getCreateTime())){
        	sql += " and createTime like '%"+record.getCreateTime()+"%'";
		}
        if(!isEmpty(record.getStatus())){
        	sql += " and status like '%"+record.getStatus()+"%'";
		}
       sql += " ORDER BY ID DESC ";
		Pager<Record> pagers = recordService.findBySqlRerturnEntity(sql);
		model.addAttribute("pagers", pagers);
		//存储查询条件
		model.addAttribute("obj", record);
		model.addAttribute("signId", record.getSignId());
		return "record/record";
	}
	
	/**
	 * 辅导员查看签到记录
	 * @param record
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/fdyRecord")
	public String fdyRecord(Record record, Model model, HttpServletRequest request, HttpServletResponse response) {
		//分页查询
		String sql = "SELECT * FROM record WHERE signId="+record.getSignId();
        if(!isEmpty(record.getSignId())){
        	sql += " and signId like '%"+record.getSignId()+"%'";
		}
        if(!isEmpty(record.getStudentId())){
        	sql += " and studentId like '%"+record.getStudentId()+"%'";
		}
        if(!isEmpty(record.getIp())){
        	sql += " and ip like '%"+record.getIp()+"%'";
		}
        if(!isEmpty(record.getCreateTime())){
        	sql += " and createTime like '%"+record.getCreateTime()+"%'";
		}
        if(!isEmpty(record.getStatus())){
        	sql += " and status like '%"+record.getStatus()+"%'";
		}
       sql += " ORDER BY ID DESC ";
		Pager<Record> pagers = recordService.findBySqlRerturnEntity(sql);
		model.addAttribute("pagers", pagers);
		//存储查询条件
		model.addAttribute("obj", record);
		model.addAttribute("signId", record.getSignId());
		return "record/fdyRecord";
	}
	
	
	//mysign
	/**
	 * 查询学生自己可以签到列表
	 * @param record
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/mysign")
	public String mysign(Record record, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		Object attribute = request.getSession().getAttribute("userId");
		
		if (attribute == null){
			return "redirect:/login/uLogin";	
		}
		Integer userId = Integer.valueOf(attribute.toString());
		
		
		//分页查询
		String sql = "SELECT * FROM record WHERE studentId="+userId;
        if(!isEmpty(record.getSignId())){
        	sql += " and signId like '%"+record.getSignId()+"%'";
		}
        if(!isEmpty(record.getStudentId())){
        	sql += " and studentId like '%"+record.getStudentId()+"%'";
		}
        if(!isEmpty(record.getIp())){
        	sql += " and ip like '%"+record.getIp()+"%'";
		}
        if(!isEmpty(record.getCreateTime())){
        	sql += " and createTime like '%"+record.getCreateTime()+"%'";
		}
        if(!isEmpty(record.getStatus())){
        	sql += " and status like '%"+record.getStatus()+"%'";
		}
       sql += " ORDER BY ID DESC ";
		Pager<Record> pagers = recordService.findBySqlRerturnEntity(sql);
		model.addAttribute("pagers", pagers);
		//存储查询条件
		model.addAttribute("obj", record);
		model.addAttribute("signId", record.getSignId());
		return "record/mysign";
	}
	
	/**
	 * 分页查询 返回list对象(通过Map)
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/findByMap")
	public String findByMap(Record record, Model model, HttpServletRequest request, HttpServletResponse response) {
		//通过map查询
		Map<String,Object> params = new HashMap<String,Object>();
        if(!isEmpty(record.getSignId())){
        	params.put("signId", record.getSignId());
		}
        if(!isEmpty(record.getStudentId())){
        	params.put("studentId", record.getStudentId());
		}
        if(!isEmpty(record.getIp())){
        	params.put("ip", record.getIp());
		}
        if(!isEmpty(record.getCreateTime())){
        	params.put("createTime", record.getCreateTime());
		}
        if(!isEmpty(record.getStatus())){
        	params.put("status", record.getStatus());
		}
		//分页查询
		Pager<Record> pagers = recordService.findByMap(params);
		model.addAttribute("pagers", pagers);
		//存储查询条件
		model.addAttribute("obj", record);
		return "record/record";
	}
	
	/**********************************【增删改】******************************************************/
	
	/**
	 * 跳至添加页面
	 * @return
	 */
	@RequestMapping(value = "/add")
	public String add() {
		return "record/add";
	}

	/**
	 * 跳至详情页面
	 * @return
	 */
	@RequestMapping(value = "/view")
	public String view(Integer id,Model model) {
		Record obj = recordService.load(id);
		model.addAttribute("obj",obj);
		return "record/view";
	}
	
	/**
	 * 添加执行
	 * @return
	 */
	@RequestMapping(value = "/exAdd")
	@ResponseBody
	public String exAdd(Record record, Model model, HttpServletRequest request, HttpServletResponse response) {
		String ipAdrress = getIp(request);
		Record obj = recordService.load(record.getId());
		
	      JSONObject j = new  JSONObject();
		//查看是否有ip冲突  0 未签到 1 已签到 2 请假
		Record r = new Record();
		r.setSignId(obj.getSignId());
		r.setIp(ipAdrress);
		
		Integer status = obj.getSign().getStatus();
		if (status == 1){
			j.put("res",3);
	   		return j.toString();
		}
		
		if (obj.getStatus() == 2){
			j.put("res", 2);
	   		return j.toString();
		}
		List<Record> listAllByEntity = recordService.listAllByEntity(r);
		
		if (!CollectionUtils.isEmpty(listAllByEntity)){
			j.put("res", 0);
	   		return j.toString();
		}else{
			obj.setCreateTime(new Date());
			obj.setIp(ipAdrress);
			obj.setStatus(1);
			j.put("res", 1);
	   		recordService.updateById(obj);
	   		return j.toString();
		}
		
		
	}
	
	private static String getIpAdrress(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if(!StringUtils.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(!StringUtils.isEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (!StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (!StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (!StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (!StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }
	
	private String getIp(HttpServletRequest request){
	    String ip = request.getHeader("X-Forwarded-For");
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("Proxy-Client-IP");
	        }
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("WL-Proxy-Client-IP");
	        }
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("HTTP_CLIENT_IP");
	        }
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	        }
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getRemoteAddr();
	        }
	    } else if (ip.length() > 15) {
	        String[] ips = ip.split(",");
	        for (int index = 0; index < ips.length; index++) {
	            String strIp = ips[index];
	            if (!("unknown".equalsIgnoreCase(strIp))) {
	                ip = strIp;
	                break;
	            }
	        }
	    }
	    return ip;
	}
	
	/**
	 * 跳至修改页面
	 * @return
	 */
	@RequestMapping(value = "/update")
	public String update(Integer id,Model model) {
		Record obj = recordService.load(id);
		model.addAttribute("obj",obj);
		return "record/update";
	}
	
	/**
	 * 添加修改
	 * @return
	 */
	
	@RequestMapping(value = "/setQd")
	public String setQd(Record record, Model model, HttpServletRequest request, HttpServletResponse response) {
		Record obj = recordService.load(record.getId());
		//1.通过实体类修改，可以多传修改条件
		obj.setStatus(2);
		recordService.updateById(obj);
		//2.通过主键id修改
		//recordService.updateById(record);
		return "redirect:/record/findBySql.action?signId="+obj.getSignId();
	}
	
	
	@RequestMapping(value = "/exUpdate")
	public String exUpdate(Record record, Model model, HttpServletRequest request, HttpServletResponse response) {
		//1.通过实体类修改，可以多传修改条件
		recordService.updateById(record);
		//2.通过主键id修改
		//recordService.updateById(record);
		return "redirect:/record/findBySql.action";
	}
	
	/**
	 * 删除通过主键
	 * @return
	 */
	@RequestMapping(value = "/delete")
	public String delete(Integer id, Model model, HttpServletRequest request, HttpServletResponse response) {
		///1.通过主键删除
		recordService.deleteById(id);
		/*以下是多种删除方式*/
//		//2.通过实体条件删除
//		recordService.deleteByEntity(record);
//		//3.通过参数删除
//     //通过map查询
//		Map<String,Object> params = new HashMap<String,Object>();
//		
//        if(!isEmpty(record.getSignId())){
//        	params.put("signId", record.getSignId());
//		}
//       
//        if(!isEmpty(record.getStudentId())){
//        	params.put("studentId", record.getStudentId());
//		}
//       
//        if(!isEmpty(record.getIp())){
//        	params.put("ip", record.getIp());
//		}
//       
//        if(!isEmpty(record.getCreateTime())){
//        	params.put("createTime", record.getCreateTime());
//		}
//       
//        if(!isEmpty(record.getStatus())){
//        	params.put("status", record.getStatus());
//		}
//       
//		recordService.deleteByMap(params);
//		//4.状态删除
//		Record load = recordService.getById(record.getId())
//		load.setIsDelete(1);
//		recordService.update(load);
		//5.状态删除
		//Record load = recordService.load(id);
		//load.setIsDelete(1);
		//recordService.updateById(load);
		return "redirect:/record/findBySql.action";
	}
	
	
}
